package com.mzy.datepackage.M2022.May.tenSix;

import com.mzy.basics.network.Utils;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.Set;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/5/18 16:13
 * @Version 1.0
 */

/**
 * 每张网卡指定一个端口发送一次数据
 */
// 发送端
public class testSender {
    public static void main(String[] args) throws IOException
    {
//        int port = 10009;

//        InetAddress inetRemoteAddr = InetAddress.getByName("224.0.0.5");

        MulticastSocket client = new MulticastSocket(10007);
        InetAddress  receiveAddress=InetAddress.getByName("224.0.0.5");
        // 加入多地址组播再发送消息
        //获取有效网卡地址
        Set<NetworkInterface> physicalNICs = Utils.getPhysicalNICs();

        System.out.println(UUID.randomUUID());
        //端口不冲突就行
        int port = 1616;
        for (NetworkInterface networkInterface : physicalNICs) {
            // 是不是每张网卡的地址都要发送一次
//            if (networkInterface.isLoopback())
//                continue;
//            if (networkInterface.getName().indexOf("eth2")>=0)
//                continue;
                byte[] msg = ("Connection successfully!!!"+networkInterface.getName()).getBytes();
                System.out.println("发送的信息所用网卡:"+networkInterface.getName());
                DatagramPacket sendPack = new DatagramPacket(msg, msg.length,receiveAddress,port);
            client.setNetworkInterface(networkInterface);
                client.send(sendPack);
        }

        // ni -> ip -> port

//        client.send(sendPack);

//        DatagramPacket sendPack = new DatagramPacket(msg, msg.length);
////        client.joinGroup(inetRemoteAddr); // 加入此组播组
//        client.send(sendPack);

        System.out.println("Client send msg complete");
        client.close();

    }
}
